package com.db.jschool.logging;

import java.util.ArrayList;
import java.util.List;

public class Logger {
	
	public static final Level DEFAULT_LEVEL = Level.INFO;
	private final String name;
	private final List<Appender> appenders = new ArrayList<>();
	private volatile Level level;
	
	public Logger(String name) {
		this.name = name;
	}
	
		
	public void log(Level level, String message, Object... args) {
		if (!isLevelEnabled(level))
			return;
		LogRecord lr = new LogRecord(Thread.currentThread().getName(), 
				this.level, 
				System.currentTimeMillis(), 
				this.name, 
				message, 
				args);
		for (Appender appender : appenders) {
			try {
				appender.publish(lr);
			} catch (InterruptedException e) {
				System.err.println("Thread has been interrupted");
			}
		}
	}
	
	public synchronized void setLevel(Level level) {
		this.level = level;
	}
	
	public Level getLevel() {
		return this.level;
	}
	
	public void addAppender(Appender appender) {
		appenders.add(appender);
	}

	public String getName() {
		return this.name;
	}
	
	public boolean isLevelEnabled(Level level) {
		return (getLevel() != Level.OFF) && (level.ordinal() >= getLevel().ordinal());
	}

}
